
//
//  MYPublishVC.m
//  MuYing
//
//  Created by tbb on 2019/7/18.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "MYPublishVC.h"
#import "MYPublishTopView.h"
#import "MYPublishAlbumVC.h"
#import "MYPublishPhotographyVC.h"
#import <JXCategoryView/JXCategoryView.h>
#import "TZImageManager.h"
#import "TZAssetCell.h"
#import "YQImagePickerBaseVC.h"
#import "TBBGCDTimer.h"
@interface MYPublishVC ()<JXCategoryViewDelegate,JXCategoryListContainerViewDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>{
    UITableView *_tableView;
}

@property (nonatomic, strong) MYPublishTopView * topView;

@property (nonatomic, strong) JXCategoryTitleView * categoryView;
@property (nonatomic, strong) JXCategoryListContainerView * listContainerView;
@property (nonatomic, copy) NSArray * titles;
@property (nonatomic, strong) NSMutableArray *albumArr;

@property (nonatomic, assign) BOOL isOpen;

@property (nonatomic, assign) BOOL isFirstAppear;

@property (nonatomic, strong) MYPublishAlbumVC *albumVC;
@property (nonatomic, strong) MYPublishPhotographyVC *photographyVC;

@property (nonatomic, assign) NSInteger photographyVCType;
@property (nonatomic, copy) NSString * GCDTimerName;

@property(nonatomic,assign) BOOL statusHiden;
@end

@implementation MYPublishVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginVideo) name:PublishVC_VIDEO_BEGIN_KEY object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endVideo) name:PublishVC_VIDEO_END_KEY object:nil];
}



-(void)beginVideo {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.topView.timeLb.hidden = NO;
        self.topView.timeLb.text = @"0s";
    });
    __block NSInteger i = 0;
    ws(self);
    self.GCDTimerName = [TBBGCDTimer execTask:^{
        i++;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.topView.timeLb.hidden = NO;
            weakself.topView.timeLb.text = [NSString stringWithFormat:@"%zds",i];
        });
    } start:1.0 interval:1.0 repeats:YES async:YES];
}
-(void)endVideo {
    self.topView.timeLb.hidden = YES;
    [TBBGCDTimer cancelTask:self.GCDTimerName];
}
-(void)setupView {
    [super setupView];
    [self.view addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(kHeight_Top_SafeArea);
        make.height.mas_equalTo(44);
    }];
    
    self.titles = @[kYQLS(@"相册"),kYQLS(@"拍照")];//,kYQLS(@"拍视频"）
    self.categoryView = [[JXCategoryTitleView alloc] init];
    self.categoryView.delegate = self;
    self.categoryView.titles = self.titles;
    self.categoryView.defaultSelectedIndex = 0;
    //    self.categoryView.cellSpacing = 82;
    self.categoryView.titleSelectedColor = kAPPThemeColor;//HexColor(0x79C4C7);
    self.categoryView.titleColor = HexColor(0xA0A0A0);
    self.categoryView.titleFont = kSystemMedium(15);
    self.categoryView.titleSelectedFont = kSystemMedium(15);
    self.categoryView.contentEdgeInsetLeft = 12;
    self.categoryView.contentEdgeInsetRight = 12;
    self.categoryView.backgroundColor = UIColor.whiteColor;
    self.categoryView.titleColorGradientEnabled = YES;
    
    self.categoryView.averageCellSpacingEnabled = YES;
    
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    
    lineView.indicatorColor = kAPPThemeColor;
    lineView.indicatorWidth = 32;
    lineView.indicatorHeight = 2.0;
    lineView.verticalMargin = 2;
    self.categoryView.indicators = @[lineView];
    
    [self.view addSubview:self.categoryView];
    
    self.listContainerView = [[JXCategoryListContainerView alloc] initWithDelegate:self];
    self.listContainerView.defaultSelectedIndex = 0;
    [self.view addSubview:self.listContainerView];
//    self.listContainerView.scrollView.delegate = self;
    self.listContainerView.scrollView.scrollEnabled = NO;
//    self.categoryView.contentScrollView = self.listContainerView.scrollView;
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.categoryView.frame = CGRectMake(0, self.view.bounds.size.height - 49-kHeight_Botton_SafeArea, self.view.bounds.size.width, 44);
    
    self.categoryView.layer.shadowColor = HexColorA(0x000000, 0.6).CGColor;
    //2.设置阴影偏移范围
    self.categoryView.layer.shadowOffset = CGSizeMake(0, 2);
    //3.设置阴影颜色的透明度
    self.categoryView.layer.shadowOpacity = 0.07;
    
    //4.设置阴影半径
    self.categoryView.layer.shadowRadius = 4;
    //5.设置阴影路径
    self.categoryView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.categoryView.bounds].CGPath;
    
    self.listContainerView.frame = CGRectMake(0, (CGRectGetMaxY(self.topView.frame)), self.view.bounds.size.width, self.view.bounds.size.height - 44-49-kHeight_Botton_SafeArea-kHeight_Top_SafeArea);
}

#pragma mark - JXCategoryViewDelegate

- (void)categoryView:(JXCategoryBaseView *)categoryView didClickSelectedItemAtIndex:(NSInteger)index {
    CGPoint point = self.listContainerView.scrollView.contentOffset;
    self.topView.titleBtn.hidden = NO;
    self.topView.nextBtn.hidden = NO;
    if (index == 2) {
        self.topView.titleBtn.hidden = YES;
        self.topView.nextBtn.hidden = YES;
        self.photographyVC.type = 2;
        self.photographyVCType = 2;
        if (self.listContainerView.scrollView.contentOffset.x == 0) {
            self.listContainerView.scrollView.contentOffset = CGPointMake(kYQPScreenWidth, point.y);
            [self.listContainerView didClickSelectedItemAtIndex:1];
        }
    }else{
        [self.photographyVC stopRecordVideo];
        if (index == 1) {
            self.photographyVC.type = 1;
            self.photographyVCType = 1;
            self.topView.titleBtn.hidden = YES;
            self.topView.nextBtn.hidden = YES;
        }
        CGPoint tepPoint = CGPointMake(kYQPScreenWidth * index, point.y);
        self.listContainerView.scrollView.contentOffset = tepPoint;
        [self.listContainerView didClickSelectedItemAtIndex:index];
    }
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    CGFloat x = scrollView.contentOffset.x;
    NSInteger index = (NSInteger)(x / kYQPScreenWidth);
    if (index != 2) {
        if (x == kYQPScreenWidth && index == 1) {
            return;
        }
        [self.categoryView selectItemAtIndex:index];
        [self.categoryView reloadCellAtIndex:index];
        [self.listContainerView didClickSelectedItemAtIndex:index];
    }

}

- (void)categoryView:(JXCategoryBaseView *)categoryView scrollingFromLeftIndex:(NSInteger)leftIndex toRightIndex:(NSInteger)rightIndex ratio:(CGFloat)ratio {
//    [self.listContainerView scrollingFromLeftIndex:leftIndex toRightIndex:rightIndex ratio:ratio selectedIndex:categoryView.selectedIndex];
}
#pragma mark - JXCategoryViewDelegate end
#pragma mark - JXCategoryListContainerViewDelegate

- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    if (index == 0) {
        MYPublishAlbumVC *albumVC = [[MYPublishAlbumVC alloc] init];
        [self addChildViewController:albumVC];
        self.albumVC = albumVC;
        return albumVC;
    }else {
        MYPublishPhotographyVC *photographyVC = [[MYPublishPhotographyVC alloc] init];
        photographyVC.type = self.photographyVCType;
        [self addChildViewController:photographyVC];
        self.photographyVC = photographyVC;
        return photographyVC;
    }
}

- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return 2;//self.titles.count;
}

#pragma mark - JXCategoryListContainerViewDelegate end

#pragma mark -- lazy
-(MYPublishTopView *)topView {
    if (!_topView) {
        _topView = [MYPublishTopView viewFromXib];
        ws(self);
        [_topView.titleBtn setTitle:kYQLS(@"所有照片") forState:(UIControlStateNormal)];
        [_topView.cancelBtn addTapAction:^(id  _Nonnull sender) {
            [weakself.navigationController dismissViewControllerAnimated:true completion:nil];
        }];
        [_topView.nextBtn addTapAction:^(id  _Nonnull sender) {
            [weakself.albumVC nextAction];
        }];
        UIImage *image = YQIMG(@"news_top_locale_d_icon");
        [_topView.titleBtn setImage:[image qmui_imageWithBlendColor:kAPPMainTitleColor] forState:(UIControlStateNormal)];
        [_topView.titleBtn addTarget:self action:@selector(selectorAllAlbums:) forControlEvents:(UIControlEventTouchUpInside)];

    }
    return _topView;
}
#pragma mark -- lazy end
-(void)selectorAllAlbums:(UIButton *)sender {
    self.isOpen = !_isOpen;
    if (![[TZImageManager manager] authorizationStatusAuthorized]) {
        return;
    }
    if (self.isOpen) {
        [UIView animateWithDuration:0.5 animations:^{
            sender.imageView.transform = CGAffineTransformMakeRotation(M_PI);
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            sender.imageView.transform = CGAffineTransformMakeRotation(M_PI*0.000001);
            self->_tableView.frame = CGRectMake(0, kYQPScreenHeight + (kYQPScreenHeight-44-kHeight_Botton_SafeArea), kYQPScreenWidth, kYQPScreenHeight-44-kHeight_Botton_SafeArea);
        }];
        return;
    }

    self.isFirstAppear = YES;
    [self configTableView];

}

- (void)configTableView {
    YQImagePickerBaseVC *imagePickerVc = [[YQImagePickerBaseVC alloc] initWithMaxImagesCount:9 delegate:nil];
    [TZImageManager manager].sortAscendingByModificationDate = NO;
    [TZImageManager manager].columnNumber = 4;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    
        [[TZImageManager manager] getAllAlbums:YES allowPickingImage:YES needFetchAssets:!self.isFirstAppear completion:^(NSArray<TZAlbumModel *> *models) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self->_albumArr = [NSMutableArray arrayWithArray:models];

                
                if (self.isFirstAppear) {
                    self.isFirstAppear = NO;
                    [self configTableView];
                }
                
                if (!self->_tableView) {
                    self->_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
                    self->_tableView.rowHeight = 70;
                    self->_tableView.tableFooterView = [[UIView alloc] init];
                    self->_tableView.dataSource = self;
                    self->_tableView.delegate = self;
                    [self->_tableView registerClass:[TZAlbumCell class] forCellReuseIdentifier:@"TZAlbumCell"];
//                    [self.view addSubview:self->_tableView];
                    
                    [self.navigationController.view addSubview:self->_tableView];
                    [self.navigationController.view bringSubviewToFront:self->_tableView];
                } else {
                    [self->_tableView reloadData];
                }
                self->_tableView.frame = CGRectMake(0, 44, kYQPScreenWidth, kYQPScreenHeight-44-kHeight_Botton_SafeArea);
            });
        }];
    });
}

#pragma mark - UITableViewDataSource && Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _albumArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TZAlbumCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TZAlbumCell"];
    cell.selectedCountButton.backgroundColor = kAPPThemeColor;
    cell.model = _albumArr[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.topView.titleBtn.imageView.transform = CGAffineTransformMakeRotation(M_PI*0.000001);
        self->_tableView.frame = CGRectMake(0, kYQPScreenHeight + (kYQPScreenHeight-44-kHeight_Botton_SafeArea), kYQPScreenWidth, kYQPScreenHeight-44-kHeight_Botton_SafeArea);
    }];

    TZAlbumModel *model = _albumArr[indexPath.row];
    self.albumVC.albumModel = model;
}

#pragma mark - UITableViewDataSource && Delegate end
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.statusHiden = YES;
    // 刷新状态栏
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];

}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.statusHiden = NO;
    // 刷新状态栏
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
}

- (BOOL)prefersStatusBarHidden{
    return self.statusHiden;
}

@end
